<script>
  $(function () {
    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = "{{env('CDN_RESOURCE')}}/js/mobile/TcPlayer-2.2.1.js"
    script.onload = function () {
      var videoMask = document.createElement('div')
      videoMask.setAttribute('id', 'videoMask')
      videoMask.className = 'video-mask'
      videoMask.innerHTML = '<div id="closeVideo" class="close-icon icon"></div><div id="videoContainer" class="video"></div>'
      document.body.appendChild(videoMask)

      // 视频对象
      var player = new TcPlayer('videoContainer', {
        m3u8: '{{$videoOption['m3u8']}}',
        autoplay: !!'{{$videoOption['autoplay']}}',
        coverpic: '{{$videoOption['coverpic']}}',
        width: '{{$videoOption['width']}}',
        height: '{{$videoOption['height']}}',
        live: !!'{{$videoOption['live']}}',
        systemFullscreen: !!'{{$videoOption['systemFullscreen']}}'
      })

      // 观看视频
      $('#playVideo').off('click').on('click', function () {
        $('#videoMask').fadeIn(300)
        player.play()
      })

      //关闭视频
      $('#closeVideo').off('click').on('click', function () {
        player.pause()
        $('#videoMask').fadeOut(300)
      })

      // 统计代码
      @if (!empty($prefix))
      // 统计前缀
      var prefix = '{{ $prefix }}'

      // 统计时间变量
      var startTime = 0, endTime = 0, watchTime = 0

      // 视频开始播放事件
      $('#videoContainer video').off('play').on('play', function () {
        console.log('video play')
        startTime = new Date()
        analytics.send({
          event: prefix + '_video_open',
          attr: {
            _c: window.localStorage.getItem('QKidsChannel')
          }
        })
      })

      // 视频结束或暂停播放事件
      $('#videoContainer video').off('pause ended').on('pause ended', function (e) {
        console.log('video ' + e.type)
        endTime = new Date()
        watchTime += (endTime - startTime) / 1000
        console.log('watch time: ' + watchTime)
        if (watchTime > parseInt('{{ $finishTime }}', 10)) {
          analytics.send({
            event: prefix + '_video_finish',
            attr: {
              _c: window.localStorage.getItem('QKidsChannel')
            }
          })
        }
        analytics.send({
          event: prefix + '_video_' + e.type,
          attr: {
            time: watchTime.toFixed(3),
            _c: window.localStorage.getItem('QKidsChannel')
          }
        })
      })
      @endif

      document.body.removeChild(script)
    }
    document.body.appendChild(script)
  })
</script>